import os

from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render,redirect
from app.models import Press, Admin, Book, BookType


# Create your views here.

def login_decorator(fun):
    def inner(request,*args,**kwargs):

        if request.session.get("login"):

            return fun(request,*args,**kwargs)

        messages.warning(request,"登录信息已过期，请重新登录")

        return redirect("/login/")

    return inner




def login(request):

    if request.method == 'GET':
        return render(request, "login.html")
    else:
        action = request.POST.get("action")
        username = request.POST.get("username")
        password = request.POST.get("password")
        if action == "登录":
            if Admin.objects.filter(username=username, password=password):
                # 登录成功    存储信息
                response = redirect("/presslist/")
                #  设置响应cookie   不安全，容易被篡改
                # response.set_cookie("login","OK")

                #  设置session
                request.session["login"] = "OK"

                return response
            else:
                return render(request, "login.html", {"msg": "您输入的账号或密码错误！"})
        elif action == "注册":
            return redirect('/register/')
            # # 注册逻辑
            # # 这里假设注册逻辑是检查用户名是否已存在，如果不存在则创建新用户
            # if Admin.objects.filter(username=username).exists():
            #     return render(request, "login.html", {"msg": "用户名已存在！"})
            # else:
            #     # 创建新用户
            #     if username == '' or password == 'None':
            #         return render(request, "login.html", {"msg": "账号名或密码不能为空！"})
            #     else:
            #         Admin.objects.create(username=username, password=password)
            #
            #     return render(request, "login.html", {"msg": "注册成功，请登录！"})
        else:
            # 未知操作
            return HttpResponse("无效请求")


def main(request):
    return render(request, "presslist.html")
@login_decorator
def pressadd(request):
    """
    增加
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, "pressadd.html")
    else:
        # 接收参数   从页面出发，回归页面
        pressname = request.POST.get("pressname")
        pressaddress = request.POST.get("pressaddress")

        # 调用ORM,执行添加请求
        if Press.objects.filter(pressname=pressname):
            return render(request,"pressadd.html",{"msg":"请不要输入相同的出版社名称！"})
        else:
            Press.objects.create(pressname=pressname,pressaddress=pressaddress)

            # 跳转页面
            return redirect("/presslist/")

def presslist(request):


    if request.session.get("login"):


        # 不需要处理参数，直接调用ORM
        # all()查询所有

        presslist = Press.objects.all()

        content = request.GET.get('content')
        if content == None:
            return render(request, "presslist.html", {"presslist": presslist})
        else:
            presslist = Press.objects.filter(pressname__icontains=content)
            # 跳转页面
            return render(request, "presslist.html", {"presslist": presslist,"content":content})
    else:
        return render(request,"login.html",{"msg":"登录过期，请重新登录"})
def pressdelete(request):
    # 参数
    id = request.GET.get("id")

    # ORM  对象状态转换
    Press.objects.filter(id=id).delete()

    # 跳转页面
    return redirect("/presslist/")
def pressupdate(request):

    if request.method == "GET":
        # 跳转到修改的页面
        id = request.GET.get("id")

        press = Press.objects.get(id=id)
        # 转发
        return render(request,"pressupdate.html",{"press":press})
    else:
        # 真正修改功能
        pressname = request.POST.get("pressname")
        pressaddress = request.POST.get("pressaddress")
        id = request.POST.get("id")

        press = Press.objects.get(id=id)

        press.pressname=pressname
        press.pressaddress=pressaddress

        press.save()


        # Press.objects.filter(id=id).update(pressname=pressname,pressaddress=pressaddress)

        return redirect('/presslist/')
    # 参数
def register(request):
    if request.method == 'GET':
        return render(request,'register.html')
    else:
        print(11)
        username = request.POST.get('username')
        print(22)
        password = request.POST.get('password')
        print(33)
        if username == '' or password == '':
            return render(request, "register.html", {"msg": "账号名或密码不能为空！"})
        else:
            Admin.objects.create(username=username,password=password)
            return render(request,'login.html',{"msg":'注册成功！'})


def bookadd(request):
    """
    增加
    :param request:
    :return:
    """
    if request.method == 'GET':

        presslist = Press.objects.all()

        return render(request, "bookadd.html",{"presslist":presslist})
    else:
        # 接收参数   从页面出发，回归页面
        bookname = request.POST.get("bookname")
        bookprice = request.POST.get("bookprice")
        bookauther = request.POST.get("bookauther")
        bookimg_obj = request.FILES.get("bookimg")
        bookimg_name = bookimg_obj.name
        bookimg_path = "static/img"
        # 拼接像数据库保存的图片路径及名称
        bookimg = os.path.join(bookimg_path,bookimg_name)
        # 文件上传（文件从本地复制到服务器）


        with open(bookimg,"wb") as f:
            for i in bookimg_obj.chunks():
                f.write(i)

        bookimg = "/"+bookimg
        # 出版社id
        press_id = request.POST.get("press_id")
        # 调用ORM,执行添加请求
        if Book.objects.filter(bookname=bookname):
            return render(request,"bookadd.html",{"msg":"请不要添加已有的书籍！"})
        else:
            Book.objects.create(bookname=bookname,bookprice=bookprice,bookauther=bookauther,bookimg=bookimg,press_id=press_id)

            # 跳转页面
            return redirect("/booklist/")
def booklist(request):

    # 不需要处理参数，直接调用ORM
    # all()查询所有

    booklist = Book.objects.all()

    content = request.GET.get('content')
    if content == None:
        return render(request, "booklist.html", {"booklist": booklist})
    else:
        booklist = Book.objects.filter(bookname__icontains=content)
        # 跳转页面
        return render(request, "booklist.html", {"booklist": booklist,"content":content})
def bookdelete(request):
    # 参数
    id = request.GET.get("id")

    # ORM  对象状态转换
    Book.objects.filter(id=id).delete()

    # 跳转页面
    return redirect("/booklist/")
def bookupdate(request):
    if request.method == "GET":
        # 跳转到修改的页面
        id = request.GET.get("id")

        book = Book.objects.get(id=id)
        presslist = Press.objects.all()
        # 转发
        return render(request, "bookupdate.html", {"book": book,"presslist":presslist})
    else:
        # 真正修改功能
        bookname = request.POST.get("bookname")
        bookprice = request.POST.get("bookprice")
        bookauther = request.POST.get("bookauther")
        id = request.POST.get("id")

        bookimg_obj = request.FILES.get("bookimg")
        print(bookimg_obj)
        if bookimg_obj:
            bookimg_name = bookimg_obj.name
            bookimg_path = "static/img"
            # 拼接像数据库保存的图片路径及名称
            bookimg = os.path.join(bookimg_path, bookimg_name)
            # 文件上传（文件从本地复制到服务器）

            with open(bookimg, "wb") as f:
                for i in bookimg_obj.chunks():
                    f.write(i)

            bookimg = "/" + bookimg
        else:
            bookimg = request.POST.get("bookimgname")

        press_id = request.POST.get("press_id")

        book = Book.objects.get(id=id)
        book.bookname = bookname
        book.bookprice = bookprice
        book.bookauther = bookauther
        book.bookimg = bookimg
        book.press_id = press_id

        book.save()

        # Press.objects.filter(id=id).update(pressname=pressname,pressaddress=pressaddress)

        return redirect('/booklist/')
def booknameisexit(request):
    bookname = request.POST.get("bookname")

    if Book.objects.filter(bookname=bookname):
        return HttpResponse("OK")


    return HttpResponse("ERROR")

def booktypelist(request):

    booktypelist = BookType.objects.all()

    content = request.GET.get('content')
    if content == None:
        return render(request, "booktypelist.html", {"booktypelist": booktypelist})
    else:
        booktypelist = BookType.objects.filter(booktypename__icontains=content)
        # 跳转页面
        return render(request, "booktypelist.html", {"booktypelist": booktypelist, "content": content})
def booktypeadd(request):
    if request.method == 'GET':

        booklist = Book.objects.all()

        return render(request, "booktypeadd.html", {"booklist": booklist})
    else:
        # 接收参数   从页面出发，回归页面
        typename = request.POST.get("typename")
        bookids = request.POST.getlist("bookids")

        #类型表
        booktype = BookType.objects.create(typename=typename)

        # 设置中间表
        booktype.books.set(bookids)


        return redirect("/booktypelist/")
def booktypeupdate(request):
    if request.method == "GET":
        # 跳转到修改的页面
        id = request.GET.get("id")

        booktype = BookType.objects.get(id=id)
        booklist = Book.objects.all()
        # 转发
        return render(request, "booktypeupdate.html", {"booktype": booktype, "booklist": booklist})
    else:
        # 真正修改功能
        typename = request.POST.get("typename")
        id = request.POST.get("id")
        bookids = request.POST.getlist("bookids")
        update_booktype = BookType.objects.get(id=id)
        update_booktype.typename = typename

        update_booktype.save()

        update_booktype.books.set(bookids)

        # Press.objects.filter(id=id).update(pressname=pressname,pressaddress=pressaddress)

        return redirect('/booktypelist/')
def booktypedelete(request):
    id = request.GET.get("id")

    # ORM  对象状态转换
    BookType.objects.filter(id=id).delete()

    # 跳转页面
    return redirect("/booktypelist/")


def requestTest(request):
    print(request)
    print(type(request))